package com.zelo.blog.server.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description token工具类
 * @Auther zhanglu
 * @Date 2017/10/13 下午4:56
 */
@Component
@Getter
@Setter
@Slf4j
public class TokenUtil {
    @Value("${token.secret}")
    private String secret; // key暂时不加密，由字符串代替
    @Value("${token.cookieAuth}")
    private String cookieAuth;//cookie存放token的名称

    public String createJWT(AuthenticationUser user, List<String> roles) {
        try {
            return Jwts.builder()
                    .setSubject(user.getUsername())
                    .setIssuer("ZhangLu")
                    .claim("expireDate", user.getExpireDate())
                    .claim("email", user.getEmail())
                    .claim("password", user.getPassword())
                    .claim("gender", user.getGender())
                    .claim("age", user.getAge())
                    .claim("idCard", user.getIdCard())
                    .claim("roles", roles.stream().collect(Collectors.joining(",")))
                    .signWith(SignatureAlgorithm.HS256, secret)
                    .compact();
        }catch (Exception e){
            log.error("", e);
            return null;
        }
    }

    public AuthenticationUser parserToken(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(claims.get("roles", String.class));
            return new AuthenticationUser(
                    claims.getSubject(),
                    claims.get("password", String.class),
                    claims.get("email", String.class),
                    claims.get("gender", Boolean.class),
                    claims.get("age", Integer.class),
                    claims.get("idCard", String.class),
                    claims.get("expireDate", Date.class),
                    token,
                    auths
            );
        }catch (Exception e){
            return null;
        }
    }

    public void setCookie(HttpServletResponse httpServletResponse, @NonNull String token) {
        Cookie cookie = new Cookie(cookieAuth, token);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 12 * 14);
        httpServletResponse.addCookie(cookie);
    }

    public void removeResponseAuthCookie(HttpServletResponse httpServletResponse) {
        // remove the auth cookie if they have it.
        Cookie cookie = new Cookie(cookieAuth, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        httpServletResponse.addCookie(cookie);
    }

    public void removeRequestAuthCookie(HttpServletRequest request) {
        Arrays.stream(request.getCookies()).forEach(cookie -> { //这里把request里面设置null
            if(cookieAuth.equalsIgnoreCase(cookie.getName())){
                cookie.setValue(null);
                cookie.setMaxAge(0);
            }
        });
    }
}
